#!/bin/bash

# 14.103.180.56服务器专用部署脚本
# 使用方法: ./deploy-14.sh

SERVER_IP="14.103.180.56"
USERNAME="root"
APP_NAME="warp-knitting-monitor"
REMOTE_DIR="/opt/$APP_NAME"
JAR_FILE="demo-0.0.1-SNAPSHOT.jar"

echo "开始部署应用到服务器: $SERVER_IP"
echo "=================================="

# 1. 编译打包
echo "1. 编译打包..."
if [ ! -f "mvnw" ]; then
    echo "❌ 错误: mvnw 不存在"
    exit 1
fi

chmod +x mvnw
./mvnw clean package -DskipTests
if [ $? -ne 0 ]; then
    echo "❌ 编译打包失败"
    exit 1
fi

if [ ! -f "target/$JAR_FILE" ]; then
    echo "❌ 错误: target/$JAR_FILE 不存在"
    exit 1
fi
echo "✅ 编译打包成功: target/$JAR_FILE"

# 2. 上传JAR文件到服务器
echo "2. 上传JAR文件到服务器..."
ssh $USERNAME@$SERVER_IP "mkdir -p $REMOTE_DIR"
if scp target/$JAR_FILE $USERNAME@$SERVER_IP:$REMOTE_DIR/; then
    echo "✅ JAR文件上传成功"
else
    echo "❌ 上传失败"
    exit 1
fi

# 3. 重启应用
echo "3. 重启应用..."
ssh $USERNAME@$SERVER_IP << EOF
    cd $REMOTE_DIR
    
    # 停止现有应用
    echo "停止现有应用..."
    pkill -f $JAR_FILE 2>/dev/null || true
    
    # 检查端口占用
    if lsof -ti:8093 > /dev/null 2>&1; then
        echo "端口8093被占用，正在停止..."
        lsof -ti:8093 | xargs kill -9 2>/dev/null || true
    fi
    
    # 等待进程完全停止
    sleep 3
    
    # 启动应用
    echo "启动应用..."
    nohup java -Xms512m -Xmx1024m -XX:+UseG1GC \\
         -jar $JAR_FILE \\
         --spring.profiles.active=prod \\
         --server.port=8093 > app.log 2>&1 &
    
    echo \$! > app.pid
    echo "应用已启动，PID: \$(cat app.pid)"
    
    # 等待应用启动
    echo "等待应用启动..."
    sleep 10
    
    # 检查应用状态
    if curl -s http://localhost:8093/api/monitor/machines > /dev/null; then
        echo "✅ 应用启动成功！"
        echo "访问地址: http://$SERVER_IP:8093"
    else
        echo "❌ 应用启动失败，请检查日志"
        echo "最后20行日志:"
        tail -20 app.log
    fi
EOF

echo "=================================="
echo "部署完成！"
echo "应用访问地址: http://$SERVER_IP:8093"
echo "查看应用日志: ssh $USERNAME@$SERVER_IP 'tail -f $REMOTE_DIR/app.log'"
echo "查看应用状态: ssh $USERNAME@$SERVER_IP 'ps aux | grep $JAR_FILE'" 